using System;
using System.Diagnostics.Contracts;
using System.Linq;

namespace ReactiveCode
{
    using Observables;

    public class ReactiveProperty<T>: IObservableValue<T>
    {
        IObservableValue<T> _value;
        public T Value
        {
            get { return _value.Value; }
            set
            {
                Contract.Requires<InvalidOperationException>(!IsReadOnly);
                var observer = _value as IObserver<T>;
                observer.OnNext(value);
            }
        }

        public bool IsReadOnly
        {
            get { return !(_value is IObserver<T>); }
        }

        Event<T> _changed;
        public event EventHandler Changed
        {
            add
            {
                if (_changed == null)
                    _changed = new Event<T>(_value, this);
                _changed.Changed += value;
            }
            remove
            {
                if (_changed != null)
                    _changed.Changed -= value;
            }
        }

        public IDisposable Subscribe(IObserver<T> observer)
        {
            return _value.Subscribe(observer);
        }

        public ReactiveProperty(IObservable<T> source)
        {
            Contract.Requires<ArgumentNullException>(source != null, "source");
            _value = source.LatestContinuous();
        }
        public ReactiveProperty(T value)
        {
            _value = new Variable<T>(value);
        }
        public ReactiveProperty()
        {
            _value = new Variable<T>();
        }

        public void Dispose()
        {
            var disposable = _value as IDisposable;
            if (disposable != null)
                disposable.Dispose();
        }
    }
}